function p=pearsonChi2Test(X)


%%%%%
% This function performs the Pearson Chi-Square Test that compares groups in terms of a categorical variable. 
%
% Input:
% X - 2D matrix where the rows and columns are explanatory (groups) and response (categories) variables, respectively.
%
% Output:
% p - p-value of the test.
% 
% Written by Joon Lee, 2011
%%%%%


% compute row sums
rowsums=zeros(size(X,1),1);
for i=1:length(rowsums)
    rowsums(i)=sum(X(i,:));
end

% compute column sums
colsums=zeros(1,size(X,2));
for i=1:length(colsums)
    colsums(i)=sum(X(:,i));
end

% total sum
totsum=sum(rowsums);

% expected counts
expX=rowsums*colsums./totsum;

% go through each cell to compute chi-square statistic
chistat=0;
for i=1:length(rowsums)
    for j=1:length(colsums)        
        chistat=chistat+(X(i,j)-expX(i,j))^2/expX(i,j);
    end
end

p=1-cdf('chi2',chistat,(size(X,1)-1)*(size(X,2)-1));
